// pages/user-shop-goods-order-medical/user-shop-goods-order-medical.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    etype:'',
    eid:'',
    imgUrl: app.globalData.imgUrl,
    roleType: wx.getStorageSync('roleType'),

    info: null,
    newmoney: '', //预约金
    promotionPrice: '', //促销价
    goodsImages:'', //商品图片

    name:'',
    headPic:'',
    core:null,
    maxCoin: '', // 美丽币
    maxPrice: '', // 抵用钱数
    balance: '', // 余额
    calculateTotalMoney:'',
    checkedBalance: false,
    checkedcoin: false,

    conceal: !1,
    provincelist: [],
    newvalue: "",
    newchecked: !1,
    
    promotionPrice: '',
    invoice:'',          // 发票信息
    orderType: '',   // 订单类型 1 术前术后 2 服务类 3 充值 4 课程
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('参数', options)
    this.setData({
      eid: options.id,
      etype: options.type
    });
    this.loadings();
    this.loaduser();
    this.beautifulCoin()
    
  },
  loadings: function() {
    let { eid, etype } = this.data;
    var that = this;
    if (etype == 1){
      var url = app.globalData.baseUrl + 'shopp/yimeiGoodsApi/getDetail/'
    }else{
      var url = app.globalData.baseUrl + 'shopp/goodsApi/goodsDetail/' 
    }
    wx.request({
      url: url + eid,
      header: {
        'sign': app.globalData.sign,
        'token': app.globalData.token,
        'content-type': 'application/json'
      },
      success(res) {
        console.log('详情', res);
        console.log('详情particulars', res.data.data.goodsDetail);
        that.setData({
          info: res.data.data.goodsDetail,
          newmoney: res.data.data.goodsDetail.reservations,
          calculateTotalMoney: res.data.data.goodsDetail.reservations,
          promotionPrice: res.data.data.goodsDetail.promotionPrice,
          goodsImages:res.data.data.goodsImages["0"],
          orderType: res.data.data.goodsDetail.goodsType
        });
      }
    })
  },
  loaduser: function() {
    //获取用户id
    var that = this;  
    wx.request({
      url: app.globalData.baseUrl + 'doctor/member/detail',
      data: {},
      header: {
        'sign': app.globalData.sign,
        'token': app.globalData.token,
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      method: 'POST',
      success: function(t) {
        console.log("个人中心1", t);
        that.setData({
          core: t.data.data[0],
          name: t.data.data[0].name,
          headPic: t.data.data[0].headPic
        })
      }
    })
  },
  // 获取美丽币
  beautifulCoin() {
    const that = this;
    app.request({
      url: "doctor/beautyCoin/getBeautyCoin",
      success: function (res) {
        that.setData({
          maxCoin: res.data.maxCoin,
          maxPrice: res.data.maxPrice,
          balance: res.data.currUser.totalMoney
        })
      },
      fail: function (res) {
        // app.requestFail(res);
      }
    });
  },
  // 协议内容
  agreement: function () {
    var id = 9;
    wx.navigateTo({
      url: '../doctor-news-system/doctor-news-system?id=' + id,
    })
  },
  // 点击同意协议
  checkboxChange: function (e) {
    console.log(e.detail.value[0]);
    this.setData({
      newvalue: e.detail.value[0]
    })
  },
  // 获取所有已开通的城市列表
  getAllCity: function (e) {
    var that = this;
    wx.request({
      url: app.globalData.baseUrl + 'doctor/city/getCityListForDoctor',
      data: {
        'type': 1,
      },
      header: {
        'sign': app.globalData.sign,
        'token': app.globalData.token,
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
      },
      method: 'POST',
      success(res) {
        console.log('全部已开通城市:', res)
        that.setData({
          'conceal': !0,
          'provincelist': res.data.data,
        });
      }
    })
  },
  updateaddress: function() {
    this.setData({
      'conceal': !0,
      'currentLevel': 1,
      'level': 2,
    })
    // 获取省
    var that = this;
    wx.request({
      url: app.globalData.baseUrl + 'doctor/city/getCityList',
      data: {},
      header: {
        'sign': app.globalData.sign,
        'token': app.globalData.token,
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
      },
      method: 'POST',
      success(res) {
        console.log('省列表:', res)
        that.setData({
          'provincelist': res.data.data,
        })
      }
    })
  },
  bindProvince: function(e) {
    var that = this;
    console.log('currentLevel', that.data.currentLevel);
    var id = e.currentTarget.dataset.provinceid;
    var name = e.currentTarget.dataset.provincename;
    this.setData({
      'cityid': id,
      'cityname': name,
      'conceal': !1,
    })
    // var id = id;
    // var level = that.data.level;
    // var currentLevel = that.data.currentLevel;
    // if (currentLevel == 1) {
    //   that.setData({
    //     'provinceid': id,
    //     'provincename': name,
    //   });
    // } else if (currentLevel == 2) {
    //   that.setData({
    //     'cityid': id,
    //     'cityname': name,
    //   });
    // } else if (currentLevel == 3) {
    //   that.setData({
    //     'districtid': id,
    //     'districtname': name,
    //   });
    // }
    // wx.request({
    //   url: app.globalData.baseUrl + 'doctor/city/getCityList',
    //   data: {
    //     id: id,
    //     level: level,
    //     currentLevel: currentLevel,
    //   },
    //   header: {
    //     'sign': app.globalData.sign,
    //     'token': app.globalData.token,
    //     'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
    //   },
    //   method: 'POST',
    //   success(res) {
    //     console.log('列表:', res)
    //     that.setData({
    //       'provincelist': res.data.data,
    //       'level': level + 1,
    //       'currentLevel': currentLevel + 1,
    //     })

    //   }
    // })
    // console.log('currentLevel', that.data.currentLevel);
    // if (that.data.currentLevel == 2) {
    //   that.setData({
    //     'conceal': !1,
    //     'currentLevel': 1,
    //     'level': 2,
    //   })
    // }
  },
  //发票信息
  invoice(orderid) {
    if (this.data.invoice) {
      const param = {
        orderNumber: orderid,
        headType: this.data.invoice.headType,
        headName: this.data.invoice.headName || '',
        identityNumber: this.data.invoice.identityNumber || ''
      };
      app.request({
        url: 'shopp/financeApi/insertInvoice',
        data: param,
        success: function (res) { },
        fail: function (res) { }
      });
    }
  },
  changeBanlanceChecked: function (e) {
    let { balance } = this.data;
    if (Number(balance) > 0) {
      let checked = !this.data.checkedBalance;
      this.setData({
        checkedBalance: checked
      });
      this.calculateTotalPrice();
    } else {
      wx.showToast({
        icon: 'none',
        title: '您的余额不足',
        duration: 1000
      });
    }
  },
  changeCoinChecked: function (e) {
    let { maxCoin } = this.data;
    if (Number(maxCoin) > 0) {
      let checked = !this.data.checkedcoin;
      this.setData({
        checkedcoin: checked
      });
      this.calculateTotalPrice();
    } else {
      wx.showToast({
        icon: 'none',
        title: '您的美丽币不足',
        duration: 1000
      });
    }
  },
  calculateTotalPrice: function () {
    let {
      newmoney,
      balance,
      maxPrice,
      checkedcoin,
      checkedBalance
    } = this.data;
    let total = Number(newmoney);
    if (checkedcoin) {
      total = total - Number(maxPrice);
      if (checkedBalance) {
        if (total - Number(balance) > 0) {
          total = total - Number(balance);
        }
      }
    } else {
      if (checkedBalance) {
        if (total - Number(balance) > 0) {
          total = total - Number(balance);
        }
      }
    }
    this.setData({
      calculateTotalMoney: total
    });
  }, 
  // 提交订单
  addroder: function() {
    var that = this;
    let { cityid, newvalue, eid, etype, info, balance, maxPrice, newmoney, checkedcoin, checkedBalance, calculateTotalMoney} = this.data;
    const invoice = wx.getStorageSync('invoice') || '';
    this.setData({
      invoice
    });
    if (!cityid) {
      wx.showToast({
        title: '请选择手术城市',
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    if (newvalue != 1) {
      wx.showToast({
        title: '请阅读协议后勾选下单',
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    if (etype == 1) {
      wx.request({
        url: app.globalData.baseUrl + 'shopp/yimeiGoodsOrderApi/submitOrder',
        data: {
          cityid: cityid,
          goodsid: eid,
          goodsnum: 1,
          reservations: newmoney,
          storepayment: info.storePayment,
          usebalance: checkedBalance ? balance : 0,
          usecoin: checkedcoin ? maxPrice : 0,
        },
        header: {
          'sign': app.globalData.sign,
          'token': app.globalData.token,
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        method: 'POST',
        success: function (res) {
          let { ifPayment, orderId } = res.data.data;
          that.invoice(orderId);
          if (ifPayment) {
            wx.navigateTo({
              url: `../user-shop-goods-order-pay/user-shop-goods-order-pay?res=${orderId}&totalMoney=${calculateTotalMoney}&payType=1&orderType=1`,
            });
          } else {
            let { actualBalance } = res.data.data;
            wx.navigateTo({
              url: `../user-shop-goods-balance-pay/user-shop-goods-balance-pay?res=${orderId}&balance=${actualBalance}`,
            });
          }
        }
      })
    } else {
      let type="";
      if (etype==2){
        type =1;
      }else{
        type=2;
      }
      var data=[];
      data[0] = { 'type': type, 'id': eid, 'unitprice': info.promotionPrice, 'number': 1};  
      wx.request({
        url: app.globalData.baseUrl + 'shopp/goodsOrderApi/submitGoodsOrder',
        data: {
          consigneeid: wx.getStorageSync('userid'),
          goodslist: JSON.stringify(data),
          goodstotalprice: info.promotionPrice,
          invoicetaxprice: 0,
          orderprice: info.promotionPrice,
          packingprice: 0,
          paymentprice: info.promotionPrice,
          transportprice: 0,
          usebalance: 0,
          usecoin: maxPrice,
        },
        header: {
          'sign': app.globalData.sign,
          'token': app.globalData.token,
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        method: 'POST',
        success: function(t) {
          console.log("提交术前术后商品订单:", t);
          // wx.navigateTo({
          //   url: '../user-shop-goods-order-pay/user-shop-goods-order-pay?res=' + t.data.data.orderid,
          // })
        }
      })
    }
  },
  //发票信息
  invoice( orderid ){
    if ( this.data.invoice ){
      const param = {
        orderNumber: orderid,
        orderType: this.data.orderType,
        headType: this.data.invoice.headType,
        headName: this.data.invoice.headName ||'', 
        identityNumber: this.data.invoice.identityNumber ||'' 
      };
      app.request({
        url: 'shopp/financeApi/insertInvoice',
        data: param,
        success: function (res) { },
        fail: function (res) { }
      });
    }
  } 
})